<template>
  <el-row v-loading="loading">
    <el-col :span="19">
      <div class="grid-content">
        <div id="mainMap" class="main-map">
        </div>
      </div>
    </el-col>
    <el-col :span="5">
      <div class="grid-content bg-purple-light">
        <el-table
          :data="baseData"
          class="customer-no-border-table"
          :header-cell-style="{'text-align':'center'}"
        >
          <el-table-column label="基地列表" prop="baseName">
            <template slot-scope="scope">
              <div style="float: left;margin-top: 3px">
                <span style="font-size: 1.8vh">{{ scope.row.baseName }}</span>
              </div>
              <div style="float: right">
                <el-button
                  size="mini"
                  icon="el-icon-map-location"
                  type="warning"
                  style="font-size: 2vh; background-color: #FFC125;"
                  @click="panToLngLat(scope.row.baseCoordinate)"
                ></el-button>
                <el-button
                  size="mini"
                  icon="el-icon-edit-outline"
                  type="primary"
                  style="font-size: 2vh; background-color: #00AFFF; color: white;"
                  @click="btnUpdate(scope.row)"
                ></el-button>
                <el-button
                  size="mini"
                  icon="el-icon-delete"
                  type="danger"
                  style="font-size: 2vh;"
                  @click="handleDelete(scope.row)"
                ></el-button>
              </div>
            </template>
          </el-table-column>
          <template v-slot:append >
            <div style="display: flex; justify-content: center; align-items: center;">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-circle-plus-outline"
                style="font-size: 2.5vh;"
                @click="btnAdd"
              >
              </el-button>
            </div>
          </template>
        </el-table>
      </div>
    </el-col>
    <!--    添加或修改基地-->
    <el-dialog :title="dialog.title" v-if="dialog.dialogVisible" :visible.sync="dialog.dialogVisible" width="1200px"
               append-to-body @opened="initBase"
    >
      <el-form ref="form" :model="baseForm" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="10" style="padding-right: 10px">
            <el-form-item label="基地简称" prop="baseShortName">
              <el-input v-model="baseForm.baseShortName" placeholder="请输入基地简称"/>
            </el-form-item>
            <el-form-item label="基地编号" prop="baseCode">
              <el-input v-model="baseForm.baseCode" placeholder="请输入基地编号"/>
            </el-form-item>
            <el-form-item label="基地全称" prop="baseName">
              <el-input v-model="baseForm.baseName" placeholder="请输入基地全称"/>
            </el-form-item>
            <el-form-item label="基地负责人" prop="baseLeader" label-position="top">
              <span><el-input v-model="baseForm.baseLeader" placeholder="请输入基地负责人"/></span>
            </el-form-item>
            <el-form-item label="基地负责人电话" prop="leaderTel">
              <el-input v-model="baseForm.leaderTel" placeholder="请输入基地负责人"/>
            </el-form-item>
            <el-form-item label="基地负责人地址" prop="baseAddress">
              <el-input v-model="baseForm.baseAddress" placeholder="请输入基地负责人"/>
            </el-form-item>
            <el-form-item label="现场图片">
              <imageUpload v-model="baseForm.baseImg" :fileSize="30" :limit="1"/>
            </el-form-item>
            <el-form-item label="基地描述" prop="baseDes">
              <el-input v-model="baseForm.baseDes" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <draw-area :polygon-coordinate="baseForm.baseCoordinate" :polygon-path="baseForm.path"
                       @change-path="getPloygon" ref="drawArea" @baseCoordinate="getBaseCoordinate"
            />
            <el-form-item label="基地坐标" prop="coordinate">
              <el-input v-model="baseForm.baseCoordinate" :disabled="true"/>
            </el-form-item>
            <el-col :span="12">
              <el-form-item label="基地海拔" prop="baseAltitude">
                <el-input v-model="baseForm.baseAltitude" placeholder="请输入基地海拔">
                  <template slot="append">米</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="基地面积" prop="baseArea">
                <el-input v-model="baseForm.baseArea" placeholder="请输入基地面积">
                  <template slot="append">亩</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>

<script>
import { addBaseinfo, delBaseinfo, getBaseinfo, listBaseinfo, updateBaseinfo } from '@/api/agriculture/baseinfo'
import DrawArea from './DrawArea'

export default {
  name: '',
  mixins: [],
  components: { DrawArea },
  props: {},
  data() {
    return {
      dialog: {
        title: '',
        dialogVisible: false,
      },
      baseForm: {},
      map: null,
      baseMap: null,
      // 默认列表第一个基地的坐标
      firstLngLat: [109.464361,22.913405],
      baseData: [],
      loading: true,
      baseCoordinate: '',
      // 表单校验
      rules: {
        baseShortName: [
          { required: true, message: '基地简称不能为空', trigger: 'blur' }
        ],
        baseCode: [
          { required: true, message: '基地编号不能为空', trigger: 'blur' }
        ],
        baseName: [
          { required: true, message: '基地全称不能为空', trigger: 'blur' }
        ],
        baseLeader: [
          { required: true, message: '基地负责人不能为空', trigger: 'blur' }
        ],
        leaderTel: [
          { required: true, message: '基地负责人电话不能为空', trigger: 'blur' }
        ],
        baseAddress: [
          { required: true, message: '基地负责人地址不能为空', trigger: 'blur' }
        ],
        baseArea: [
          { required: true, message: '基地面积不能为空', trigger: 'blur' }
        ],
        baseAltitude: [
          { required: true, message: '基地海拔不能为空', trigger: 'blur' }
        ],
      }
    }
  },
  computed: {},
  watch: {
    baseData(newValue){
      if (newValue !== undefined) {
        this.initMap();
      }
    }
  },
  async mounted() {
    await this.getListBaseinfo()
  },
  methods: {
    //创建添加框的小地图
    initBase() {
      if (this.baseMap === null) {
        this.baseMap = new T.Map('baseMap')
        this.baseMap.centerAndZoom(new T.LngLat(this.firstLngLat[0], this.firstLngLat[1]), 16)
        this.baseMap.addControl(new T.Control.Zoom)
        this.baseMap.setMapType(window.TMAP_HYBRID_MAP)
        this.baseMap.disableDoubleClickZoom()
      }
    },

    // 初始化map
    initMap() {
      if (this.map == null) {
        this.map = new T.Map('mainMap')
        this.map.centerAndZoom(new T.LngLat(this.firstLngLat[0], this.firstLngLat[1]), 16)
        this.map.addControl(new T.Control.Zoom)
        this.map.setMapType(window.TMAP_HYBRID_MAP)
        this.map.disableDoubleClickZoom()
      }

      // 展示基地范围
      this.baseData.forEach(item => {
        let { path } = item
        let itemPath = path && path.split('|').map(item => item.split(','))
        let TPath = []
        itemPath.forEach(item => {
          TPath.push(new T.LngLat(parseFloat(item[0]).toFixed(6), parseFloat(item[1]).toFixed(6)))
        })
        let polygon = new T.Polygon(TPath, {
          color: 'cyan',
          weight: 2,
          opacity: 1,
          fillColor: 'cyan',
          fillOpacity: 0.5,
          lineStyle: 'solid'
        })
        this.map.addOverLay(polygon)
      })
    },

    // 按钮方法
    // 定位到基地
    panToLngLat(baseCoordinate) {
      if (baseCoordinate !== '') {
        this.firstLngLat = baseCoordinate.split(', ')
        this.map.panTo(new T.LngLat(this.firstLngLat[0], this.firstLngLat[1]))
      }else {
        this.$message.error('定位地址为空，或数据出错，请联系管理员查看');
      }
    },
    // 添加
    btnAdd() {
      this.reset()
      this.dialog.dialogVisible = true
      this.dialog.title = '添加基地'
    },
    // 修改
    btnUpdate(row) {
      let landId = row.baseId
      getBaseinfo(landId).then((response) => {
        this.baseForm = response.data
        this.dialog.dialogVisible = true
        this.dialog.title = '修改基地'
      })
      this.loading = false
    },
    // 提交按钮
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.baseForm.baseId != null) {
            updateBaseinfo(this.baseForm).then((response) => {
              console.log(this.baseForm)
              this.$modal.msgSuccess('修改成功')
              this.$data.dialog.dialogVisible = false
              this.getListBaseinfo()
            })
          } else {
            addBaseinfo(this.baseForm).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.$data.dialog.dialogVisible = false
              this.getListBaseinfo()
            })
          }
          this.getBaseList()
        }
      })
    },
    // 删除按钮
    handleDelete(form) {
      this.$confirm('此操作将删除 ' + form.baseName + ' 基地, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delBaseinfo(form.baseId)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        setTimeout(() =>{
          this.loading = true
          this.getBaseList()
        },100)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 发请求方法
    async getListBaseinfo() {
      if (this.$data.baseData.length === 0) {
        this.loading = false;
      }
      const { rows } = await listBaseinfo()
      this.$data.baseData = rows
      let lnglat = this.$data.baseData[0].baseCoordinate
      if (lnglat != '') {
        this.$data.firstLngLat = lnglat.split(',')
      }
    },

    // 重新加载基地列表
    getBaseList() {
      this.loading = true
      // 重新获取数据
      this.getListBaseinfo()
      this.map.clearOverLays()
      setTimeout(() => {
        this.initMap()
        this.loading = false
      },1000)
    },
    // 表单重置
    reset() {
      this.baseForm = {
        baseCoordinate: '110.7351, 24.497',
        path: ''
      }
      this.resetForm('form')
    },
    /** 获取多边形数据 */
    getPloygon(p) {
      this.baseForm.path = p.join('|')
    },
    /** 获取多边形数据 */
    getBaseCoordinate(p) {
      console.log(p)
      this.baseForm.baseCoordinate = p
    }
  }
}
</script>
<style lang="scss" scoped>
.main-map {
  height: 99%;
}

.grid-content {
  border-radius: 4px;
  height: 91vh;
}

</style>
